package com.tc.tickets.push;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.tc.tickets.push.JPushUtil;
import com.tc.tickets.push.PushDebugUtil;

import java.security.PublicKey;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


/**
 * YaoWen(43194) create at tongcheng work pc,
 * time:  2017/2/28 10:50  qq:2669932513
 *
 *  使用的极光推送账号密码
 *  jpush
   登录名：uulux1234
    密码：1234uulux4321
 */
public class Push {

    public static final String TAG = "JPushInterface, Push";

    private Context mContext;

    public Push(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 设置debug模式
     * @param debugEnable
     */
    public static void setDebugMode(boolean debugEnable){
        PushDebugUtil.i(TAG, "setDebugMode(" + debugEnable + ")");
        JPushInterface.setDebugMode(debugEnable);
    }

    /**
     * 初始化，一般放在 Application 当中
     * @param context  应用的 ApplicationContext
     */
    public static void init(Context context){
        PushDebugUtil.i(TAG, "init()");
        JPushInterface.init(context);
    }

    /**
     * 设置 别名,alias
     * @param alias
     * @return
     */
    public void setAlias(String alias){
        if (!JPushUtil.isValidTagAndAlias(alias)){
            String errMsg  = "setAlias() error is wrong, alias = " + alias;
            PushDebugUtil.e(TAG, errMsg);
            PushDebugUtil.showToast(mContext, errMsg);
            return;
        }

        //如果我们之前已经设置过了，那么这里就不用再设置了
        String aliasFromSp = JPushUtil.getAliasFromSp(mContext);
        if (alias.equals(aliasFromSp)){
            String info = "alias haved stored, alias =" + alias;
            PushDebugUtil.i(TAG, info);
            PushDebugUtil.showToast(mContext, info);
            return;
        }

        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    /**
     * 设置标签，tags
     * @param tags
     */
    public void setTags(Set<String> tags){
        for (String tag : tags){
            if (!JPushUtil.isValidTagAndAlias(tag)){
                String errMsg  = "setTags() error is wrong, tags = " + tags + "\t\t" + "errorTag=" + tag;
                PushDebugUtil.e(TAG, errMsg);
                PushDebugUtil.showToast(mContext, errMsg);
                return;
            }
        }
        //Todo
        //我们应该判断一下 ，这里是否已经存储过了

        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tags));
    }

    /**
     * 统计分析API，用于 “用户使用时长”，“活跃用户”，“用户打开次数”的统计
     * @param context
     */
    public static void onResume(final Context context){
        JPushInterface.onResume(context);
    }

    /**
     * 统计分析API，用于 “用户使用时长”，“活跃用户”，“用户打开次数”的统计
     * @param context
     */
    public static void onPause(final Context context){
        JPushInterface.onPause(context);
    }

    /**
     *  调用了本 API 后，推送服务完全被停止
     * @param context  应用的 ApplicationContext
     */
    public static void stopPush(Context context){
        JPushInterface.stopPush(context);
    }

    /**
     *  调用了此 API 后，推送完全恢复正常工作。
     * @param context  应用的 ApplicationContext
     */
    public static void resumePush(Context context){
        JPushInterface.resumePush(context);
    }

    /**
     *  用来检查 Push Service 是否已经被停止
     * @param context  应用的 ApplicationContext
     * @return
     */
    public static boolean isPushStopped(Context context){
        return JPushInterface.isPushStopped(context);
    }

    /**
     *  开启CrashLog上报
     * @param context  应用的 ApplicationContext
     */
    public static void initCrashHandler(Context context){
       JPushInterface.initCrashHandler(context);
    }



    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;

    private final Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_SET_ALIAS:
                    PushDebugUtil.i(TAG, "set alias in handler");
                    JPushInterface.setAlias(mContext, (String)msg.obj, mAliasCallback);
                    break;
                case MSG_SET_TAGS:
                    PushDebugUtil.i(TAG, "set tags in handler");
                    JPushInterface.setTags(mContext, (Set<String>)msg.obj, mTagsCalback);
                    break;
                default:
                    PushDebugUtil.e(TAG, "mHandler unhandled msg -" + msg.obj);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code){
                case 0:
                    logs = "set alias success";
                    PushDebugUtil.i(TAG, logs);
                    JPushUtil.saveAliasToSp(mContext, alias);
                    break;
                case 6002:
                    logs = "Failed to set alias due to timeout. Try again after 60s.";
                    PushDebugUtil.w(TAG, logs);
                    if (JPushUtil.isConnected(mContext)){
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000*60);
                    }else {
                        logs = "mAliasCallback   no network ";
                        PushDebugUtil.w(TAG, logs);
                    }
                    break;
                default:
                    logs = "set alias Failed with errorCode = "  + code;
                    PushDebugUtil.e(TAG, logs);
            } //end of "switch "
            PushDebugUtil.showToast( mContext,logs);
        }
    };

    private final TagAliasCallback mTagsCalback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alis, Set<String> tags) {
            String logs;
            switch (code){
                case 0:
                    logs = "set tags success";
                    PushDebugUtil.i(TAG, logs);

                    //Todo
                    //我们已经将 tags存储起来，如果已经注册过了，那么这里就不用再注册了

                    break;
                case 6002:
                    logs = "set tags Failed  due to timeout. Try again after 60s.";
                    PushDebugUtil.w(TAG, logs);
                    if (JPushUtil.isConnected(mContext)){
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000*60);
                    }else {
                        logs = "mTagsCalback   no network ";
                        PushDebugUtil.w(TAG, logs);
                    }
                    break;
                default:
                    logs = "set tags Failed with errorCode = "  + code;
                    PushDebugUtil.e(TAG, logs);
            } //end of "switch "
            PushDebugUtil.showToast( mContext,logs);
        }
    };

}
